package server;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.handler.codec.http.HttpRequest;

import srmi.NativeInvoker;
import srmi.ShareMethod;

public class ServerHandler extends SimpleChannelUpstreamHandler {

	private NativeInvoker invoker;

	public ServerHandler(NativeInvoker invoker) {
		this.invoker = invoker;
	}
	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e){
		//系统时间，用于日志处理
		long startTime = System.currentTimeMillis();
		
		HttpRequest request = (HttpRequest) e.getMessage();
		ObjectInputStream ois;
		try {
			ois = new ObjectInputStream(new ByteArrayInputStream(request.getContent().array()));
			ShareMethod sm = (ShareMethod) ois.readObject();
			invoker.invoke(sm);
		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (ClassNotFoundException e2) {
			e2.printStackTrace();
		}
		
		
//		Channel channel = e.getChannel();
		
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception{
		Throwable cause = e.getCause();
		cause.printStackTrace();
	}
}
